﻿/*
 * @author: wizardc
 */

using System.Collections.Generic;
using System.IO;
using System.Text;
using DouEditor.Utils;
using UnityEditor;
using UnityEditor.Compilation;
using UnityEngine;

namespace DouEditor.Resource
{
    /// <summary>
    /// 创建 link.xml
    /// </summary>
    public class BuildStep_LinkXml : BuildStepBase
    {
        private const string BlackFilePath = "Assets/LinkBlackName.txt";
        private const string LinkFilePath = "Assets/link.xml";
        
        protected override void Start()
        {
            var blackNames = GetBlackNames();
            
            var allNameSet = new HashSet<string>();
            CollectDll(allNameSet);
            CollectAsmdef(allNameSet);
            
            var stringBuilder = new StringBuilder();
            stringBuilder.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            stringBuilder.AppendLine("<linker>");
            foreach (var name in allNameSet)
            {
                if (blackNames.Contains(name))
                {
                    stringBuilder.AppendLine($"    <assembly fullname=\"{name}\" preserve=\"all\"/>");
                }
            }
            stringBuilder.Append("</linker>");
            EditorUtil.SaveTxtFile(LinkFilePath, stringBuilder.ToString());
            AssetDatabase.Refresh();
            
            Complete();
        }

        private HashSet<string> GetBlackNames()
        {
            var result = new HashSet<string>();
            if (File.Exists(BlackFilePath))
            {
                var lines = File.ReadLines(BlackFilePath);
                foreach (var line in lines)
                {
                    if (!string.IsNullOrWhiteSpace(line))
                    {
                        result.Add(line.Trim());
                    }
                }
            }
            return result;
        }

        private void CollectDll(HashSet<string> allNameSet)
        {
            var files = Directory.GetFiles(Application.dataPath, "*.dll", SearchOption.AllDirectories);
            foreach (var file in files)
            {
                allNameSet.Add(Path.GetFileNameWithoutExtension(file));
            }
        }

        private void CollectAsmdef(HashSet<string> allNameSet)
        {
            var assemblies = CompilationPipeline.GetAssemblies(AssembliesType.PlayerWithoutTestAssemblies);
            foreach (var assembly in assemblies)
            {
                allNameSet.Add(assembly.name);
            }
        }
    }
}
